<template>
  <div>
    <!-- 面包屑到导航区 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>商品分类</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card>
      <!-- 添加按钮区域 -->
      <el-row>
        <el-col :span="2">
          <el-button type="primary" @click="addTypeData">添加分类</el-button>
        </el-col>
      </el-row>
      <!-- 表格区域 -->
      <tree-table
        ref="table"
        show-index
        border
        sum-text="sum"
        index-text="#"
        :data="goodsList"
        :columns="columns"
        :selection-type="false"
        :expand-type="false"
        :show-row-hover="false"
        class="treeTable"
      >
        <template slot="isok" slot-scope="scope">
          <i
            class="el-icon-success"
            v-if="scope.row.cat_deleted === false"
            style="color: green"
          ></i>
          <i class="el-icon-error" v-else style="color: red"></i>
        </template>
        <template slot="sort" slot-scope="scope">
          <el-tag size="mini" v-if="scope.row.cat_level === 0">一级</el-tag>
          <el-tag
            type="success"
            size="mini"
            v-else-if="scope.row.cat_level === 1"
            >二级</el-tag
          >
          <el-tag type="warning" size="mini" v-else>三级</el-tag>
        </template>
        <template slot="operate" slot-scope="scope">
          <el-button
            type="primary"
            icon="el-icon-edit"
            size="mini"
            @click="editCateInfo(scope.row.cat_id)"
          ></el-button>
          <el-button
            type="danger"
            icon="el-icon-delete"
            size="mini"
            @click="removeCateById(scope.row, scope.row.cat_id)"
          ></el-button>
        </template>
      </tree-table>
      <!-- 分页区域 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[3, 5, 10, 15]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </el-card>
    <!-- 添加分类弹窗 -->
    <el-dialog
      title="添加分类"
      :visible.sync="addTypeDialogVisible"
      width="50%"
      @close="addCateDialogClosed"
    >
      <el-form
        :model="addCateForm"
        ref="addCateFormRef"
        label-width="80px"
        :rules="addTypeFormrules"
      >
        <el-form-item label="分类名称" prop="cat_name">
          <el-input v-model="addCateForm.cat_name"></el-input>
        </el-form-item>
        <el-form-item label="父级分类">
          <el-cascader
            v-model="selectedCates"
            :options="parentList"
            :props="cascaderProps"
            @change="selectHandleChange"
            clearable
            change-on-select
          ></el-cascader>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addTypeDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addCate">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 编辑商品分类信息的弹窗 -->
    <el-dialog
      title="修改分类"
      :visible.sync="editCateDialogVisible"
      width="50%"
    >
      <el-form
        :model="editCateForm"
        ref="editCateFormRef2"
        label-width="80px"
        :rules="addTypeFormrules"
      >
        <el-form-item label="分类名称" prop="cat_name">
          <el-input v-model="editCateForm.cat_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editCateDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editCateDialogClosed"
          >确 定</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      // 商品数据
      goodsList: [],
      // 查询参数
      queryInfo: {
        type: 3,
        pagenum: 1,
        pagesize: 5,
      },
      // 总数据
      total: 0,
      // 编辑商品分类信息的弹窗
      editCateDialogVisible: false,
      // 展示添加分类的对话框
      addTypeDialogVisible: false,
      // parentList 父级分类列表
      parentList: [],
      // 添加分类数据
      addCateForm: {
        cat_name: '',
        // 父级分类id
        cat_pid: 0,
        // 分类等级 0一级分类，1二级分类以此类推
        cat_level: 0,
      },
      editCateForm: {
        cate_id: '',
        cat_name: '',
      },
      // 添加分类名称的规则
      addTypeFormrules: {
        cat_name: [
          { required: true, message: '请输入分类名称', trigger: 'blur' },
        ],
      },
      addTypeFormrules2: {
        cat_name: [
          { required: true, message: '请输入分类名称', trigger: 'blur' },
        ],
      },
      // 被选中的数据下拉框
      selectedCates: [],
      // 组件cascader的配置对象内容
      cascaderProps: {
        expandTrigger: 'hover',
        value: 'cat_id',
        label: 'cat_name',
        children: 'children',
      },
      columns: [
        {
          label: '分类名称',
          prop: 'cat_name',
          width: '400px',
        },
        {
          label: '是否有效',
          type: 'template',
          template: 'isok',
        },
        {
          label: '排序',
          type: 'template',
          template: 'sort',
        },
        {
          label: '操作',
          type: 'template',
          template: 'operate',
        },
      ],
    }
  },
  created() {
    this.getGoodsList()
  },
  methods: {
    // 获取总体商品的信息
    async getGoodsList() {
      const { data: res } = await this.$http.get('categories', {
        params: {
          type: this.queryInfo.type,
          pagenum: this.queryInfo.pagenum,
          pagesize: this.queryInfo.pagesize,
        },
      })
      if (res.meta.status !== 200) {
        this.$message.error('获取数据失败:' + res.meta.msg)
      }
      this.goodsList = res.data.result
      this.total = res.data.total
    },
    // 监听pagesize改变
    handleSizeChange(newSize) {
      this.queryInfo.pagesize = newSize
      this.getGoodsList()
    },
    handleCurrentChange(newPage) {
      this.queryInfo.pagenum = newPage
      this.getGoodsList()
    },
    // 弹出添加分类的弹窗
    addTypeData() {
      this.addTypeDialogVisible = true
      this.getParentCateList()
    },
    // 获取父级分类的数据列表
    async getParentCateList() {
      const { data: res } = await this.$http.get('categories', {
        params: {
          type: 2,
        },
      })
      if (res.meta.status !== 200) {
        this.$message.error('获取数据失败:' + res.meta.msg)
      }
      this.parentList = res.data
    },
    // 监听下拉框选中事件
    selectHandleChange() {
      if (this.selectedCates.length > 0) {
        // 父级分类的id
        this.addCateForm.cat_pid =
          this.selectedCates[this.selectedCates.length - 1]
        this.addCateForm.cat_level = this.selectedCates.length
        return false
      } else {
        this.addCateForm.cat_pid = 0
        this.addCateForm.cat_level = 0
      }
    },
    // 添项目分类
    addCate() {
      this.$refs.addCateFormRef.validate(async (valid) => {
        if (!valid) {
          return this.$message.error('输入信息有误，请检查后再试')
        }
        const { data: res } = await this.$http.post('categories', {
          cat_pid: this.addCateForm.cat_pid,
          cat_name: this.addCateForm.cat_name,
          cat_level: this.addCateForm.cat_level,
        })
        // 实现添加用户的网络请求
        if (res.meta.status !== 201) {
          this.$message.error('添加用户失败')
        }
        console.log(res)
        this.$message.success('添加成功')
        this.addTypeDialogVisible = false
        this.getGoodsList()
      })
    },
    // 监听添加分类对话框关闭 重置表单数据
    addCateDialogClosed() {
      this.$refs.addCateFormRef.resetFields()
      this.selectedCates = []
      this.addCateForm.cat_pid = 0
      this.addCateForm.cat_level = 0
      this.addCateForm.cat_name = ''
    },
    // 修改每个商品分类的信息
    editCateInfo(id) {
      console.log(id)
      this.editCateDialogVisible = true
      this.editCateForm.cat_id = id
    },
    // 监听编辑分类信息对话框关闭的事件
    editCateDialogClosed() {
      this.$refs.editCateFormRef2.validate(async (valid) => {
        console.log(valid)
        if (!valid) {
          return this.$message.error('输入信息有误，请检查后再试')
        }
        const { data: res } = await this.$http.put(
          'categories/' + this.editCateForm.cat_id,
          {
            cat_name: this.editCateForm.cat_name,
          }
        )
        // 实现添加用户的网络请求
        if (res.meta.status !== 200) {
          this.$message.error('添加用户失败')
        }
        this.$message.success('名称修改成功')
        this.editCateDialogVisible = false
        this.getGoodsList()
      })
    },
    // 删除商品分类
    async removeCateById(role, rightId) {
      const confirmResult = await this.$confirm(
        '此操作将永久删除该用户权限, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }
      ).catch((err) => err)
      if (confirmResult !== 'confirm') {
        return this.$message.info('已取消删除')
      }
      const { data: res } = await this.$http.delete(
        `categories/${rightId}`
      )
      if (res.meta.status !== 200) {
        this.$message.error('删除商品分类失败')
      }
      this.$message.success('删除商品分类成功')
      this.getGoodsList()
    },
  },
}
</script>

<style lang="less">
.treeTable {
  margin-top: 20px;
}
.el-cascader {
  width: 100%;
}
</style>
